{{ header }}
<div id="product-product" class="container">
    {#{{ include(helper.template('_partial/breadcrumb')) }}#}
    <div class="row">{{ column_left }}
        {% if column_left and column_right %}
            {% set class = 'col-sm-6' %}
        {% elseif column_left or column_right %}
            {% set class = 'col-sm-9' %}
        {% else %}
            {% set class = 'col-sm-12' %}
        {% endif %}
        <div id="content" class="{{ class }}">{{ content_top }}
            <div class="row">
                <div class="col-sm-5">
                    {% if images %}
                        {% set first = images|first %}
                        <div class="elevate-zoom-preview">
                            <a href="{{ first.popup }}">
                                <img id="elevate-zoom" src="{{ first.preview }}" data-zoom-image="{{ first.popup }}" class="img-responsive">
                            </a>
                        </div>
						{% if helper.hasTryonModel(product_id) %}
                            <div class="tryon-button">
                                <i class="glass-icon"></i>
                                <span>{{ text_tryon }}</span>
                            </div>
						{% endif %}

                        {% if product_video_url %}
                            <div id="player-wrapper">
                                <div id="player-content"></div>
                                <div id="player-close"></div>
                            </div>
                            <div id="player-play"></div>
                        {% endif %}

                        <ul class="thumbnails list-inline" id="product-thumbnail-gallery">
                            {% for image in images %}
                                <li class="image-additional">
                                    <a class="thumbnail elevatezoom-gallery"
                                       rel="group"
                                       data-image="{{ image.preview }}"
                                       data-zoom-image="{{ image.popup }}"
                                       href="{{ image.popup }}"
                                       title="{{ heading_title }}">
                                        <img src="{{ image.thumb }}"
                                             title="{{ heading_title }}"
                                             alt="{{ heading_title }}" />
                                    </a>
                                </li>
                            {% endfor %}
                        </ul>
                    {% endif %}
                </div>
                <div class="col-sm-7 product-description product-detail-right">
                    <h1>{{ heading_title }}</h1>
                    {% if review_status %}
                        <div class="stars-box">
                            <div class="rating">
                                {% for i in 1..5 %}
                                    <span class="fa fa-stack"><i class="fa fa-star fa-stack-1x {{ rating < i ? 'off' }}"></i></span>
                                {% endfor %}
                            </div>
                            <div class="more-review">
                                <a href="javascript:void(0);">{{ reviews }}</a>
                                {#/ <a href="javascript:void(0);">{{ text_write }}</a>#}
                            </div>
                        </div>
                    {% endif %}
                    <div class="product-price-wrapper">
                        {% if not special %}
                            <span class="price-new">{{ price }}</span>
                        {% else %}
                            <span class="price-new">{{ special }}</span>
                            <span class="price-old" style="text-decoration: line-through;">{{ price }}</span>
                        {% endif %}
                        {% if points %}
                            <span class="points">{{ text_points }} {{ points }}</span>
                        {% endif %}
                    </div>
                    <div class="list-unstyled product-attribute clearfix">
                        {% if manufacturer %}
                            <div class="nowrap" title="{{ manufacturer }}"><span class="title">{{ text_manufacturer }}</span> <a href="{{ manufacturers }}"><span>{{ manufacturer }}</span></a></div>
                        {% endif %}
                        <div class="nowrap" title="{{ model }}"><span class="title">{{ text_model }}</span> <span>{{ model }}</span></div>
                        {#{% if reward %}#}
                            {#<div class="nowrap" title="{{ reward }}"><span class="title">{{ text_reward }}</span> <span>{{ reward }}</span></div>#}
                        {#{% endif %}#}
                        <div class="nowrap" title="{{ stock }}"><span class="title">{{ text_stock }}</span> <span>{{ stock }}</span></div>
                    </div>
                    {% if tax or discounts %}
                        <ul class="tax-discounts-box clearfix">
                            {% if tax %}
                                <li>{{ text_tax }}{{ tax }}</li>
                            {% endif %}

                            {% if discounts and not special %}
                                {% for discount in discounts %}
                                    <li><span class="discount-quantity">{{ discount.quantity }}</span>{{ text_discount|replace({'价格：': ''}) }} / <span class="discount-price">{{ discount.price }}</span></li>
                                {% endfor %}
                            {% endif %}
                        </ul>
                    {% endif %}
                    {% if options %}
                        {% set padding_bottom="has-padding-bottom" %}
                        {% set margin_top="has-margin-top" %}
                    {% endif %}
                    <div id="product" class="{{ margin_top }} {{ padding_bottom }}">
                        {% include(helper.template('_partial/product/options')) %}
                        <div class="form-group product-cart-action">
                            <div class="quantity-input-wrapper">
                                <a href="#" class="quantity-down">-</a>
                                <input type="text" name="quantity" value="{{ minimum }}" size="2" id="input-quantity" class="form-control" />
                                <a href="#" class="quantity-up">+</a>
                                <input type="hidden" name="product_id" value="{{ product_id }}" />
                            </div>

                            <button type="button" id="button-cart" data-loading-text="{{ text_loading }}" class="btn btn-primary">
                                <i class="cart-icon"></i>
                                <span>{{ button_cart }}</span>
                            </button>

                            <div class="wishlist-share">
								{% if helper.inCompareList(product_id) %}
									<button type="button" class="compare btn btn-default disabled" data-toggle="tooltip" title="{{ button_compare }}"  disabled></button>
								{% else %}
									<button type="button" class="compare btn btn-default" data-toggle="tooltip" title="{{ button_compare }}" onclick="compare.add(event, '{{ product_id }}');"></button>
								{% endif %}
                                {#{% if helper.inCompareList(product_id) %}#}
                                    {#<button disabled type="button" data-toggle="tooltip" class="btn btn-default" title="{{ button_compare }}" onclick="compare.add(event, '{{ product_id }}');"><i class="contrast-icon"></i></button>#}
                                {#{% else %}#}
                                    {#<button type="button" data-toggle="tooltip" class="btn btn-default" title="{{ button_compare }}" onclick="compare.add(event, '{{ product_id }}');"><i class="contrast-icon"></i></button>#}
                                {#{% endif %}#}

                                {% if helper.inWishList(product_id) %}
                                    <button type="button" data-toggle="tooltip" class="favor btn btn-default is-favor" data-wish="{{ helper.inWishList(product_id) }}" data-cancel="{{ button_cancel }}" data-title="{{ button_wishlist }}" title="{{ button_cancel }}{{ button_wishlist }}" onclick="wishlist.remove(event, '{{ product_id }}');"></button>
								{% else %}
                                    <button type="button" data-toggle="tooltip" class="favor btn btn-default" data-wish="{{ helper.inWishList(product_id) }}" data-cancel="{{ button_cancel }}" data-title="{{ button_wishlist }}" title="{{ button_wishlist }}" onclick="wishlist.add(event, '{{ product_id }}');"></button>
								{% endif %}

                            </div>
                        </div>
                    </div>
                    {#{{ include(helper.template('_partial/share'), {share_url: share}) }}#}
					{% if minimum > 1 %}
                        <div class="info-area"><i class="fa fa-info-circle"></i> {{ text_minimum }}</div>
					{% endif %}
                </div>
            </div>
            <ul class="product-tabs clearfix list-unstyled">
                <li class="active"><a href="#tab-description" data-toggle="tab">{{ tab_description }}</a></li>
                {% if attribute_groups %}
                    <li><a href="#tab-specification" data-toggle="tab">{{ tab_attribute }}</a></li>
                {% endif %}
                {% if review_status %}
                    <li><a href="#tab-review" data-toggle="tab">{{ tab_review }}</a></li>
                {% endif %}
            </ul>
            <div class="tab-content">
                <div class="tab-pane active" id="tab-description">{{ description }}</div>
                {% if attribute_groups %}
                    <div class="tab-pane" id="tab-specification">
                        <table class="table table-bordered">
                            {% for attribute_group in attribute_groups %}
                                <thead>
                                <tr><td colspan="2"><strong>{{ attribute_group.name }}</strong></td></tr>
                                </thead>
                                <tbody>
                                {% for attribute in attribute_group.attribute %}
                                    <tr><td>{{ attribute.name }}</td><td>{{ attribute.text }}</td></tr>
                                {% endfor %}
                                </tbody>
                            {% endfor %}
                        </table>
                    </div>
                {% endif %}
                {% if review_status %}
                    <div class="tab-pane" id="tab-review">
                        <form class="form-horizontal" id="form-review">
                            <div id="review"></div>
                            {#{{ include(helper.template('_partial/product/review_form')) }}#}
                        </form>
                    </div>
                {% endif %}
            </div>
            {% if products %}
                <div class="related-goods">
                    <h3 class="widget-title"><span>{{ text_related }}</span></h3>
                    <div class="row no-gutters clearfix">
                        <div class="product-wrapper">
                            {% set i = 0 %}
                            {% for product in products %}
                                {% if column_left and column_right %}
                                    {% set class = 'product-layout product-grid col-xs-8 col-sm-6' %}
                                {% elseif column_left or column_right %}
                                    {% set class = 'product-layout product-grid col-xs-6 col-md-4' %}
                                {% else %}
                                    {% set class = 'product-layout product-grid col-xs-6 col-sm-3' %}
                                {% endif %}
                                <div class="{{ class }}">
                                    {{ include(helper.template('_partial/product/product_single')) }}
                                </div>
                                {#{% if column_left and column_right and (i + 1) % 2 == 0 %}#}
                                    {#<div class="clearfix visible-md visible-sm"></div>#}
                                {#{% elseif column_left or column_right and (i + 1) % 3 == 0 %}#}
                                    {#<div class="clearfix visible-md"></div>#}
                                {#{% elseif (i + 1) % 4 == 0 %}#}
                                    {#<div class="clearfix visible-md"></div>#}
                                {#{% endif %}#}
                                {% set i = i + 1 %}
                            {% endfor %}
                        </div>
                    </div>
                </div>
            {% endif %}
            {#{% if tags %}#}
                {#<p>{{ text_tags }}#}
                    {#{% for i in 0..tags|length %}#}
                        {#{% if i < (tags|length - 1) %} <a href="{{ tags[i].href }}">{{ tags[i].tag }}</a>,#}
                        {#{% else %} <a href="{{ tags[i].href }}">{{ tags[i].tag }}</a> {% endif %}#}
                    {#{% endfor %} </p>#}
            {#{% endif %}#}
            {#{% if tags %}#}
                {#<p>{{ text_tags }}#}
                    {#{% for i in 0..tags|length %}#}
                        {#{% if i < (tags|length - 1) %} <a href="{{ tags[i].href }}">{{ tags[i].tag }}</a>,#}
                        {#{% else %} <a href="{{ tags[i].href }}">{{ tags[i].tag }}</a> {% endif %}#}
                    {#{% endfor %} </p>#}
            {#{% endif %}#}
            {{ content_bottom }}
		</div>
        {{ column_right }}
	</div>

	<!-- 模态框（Modal） -->
	<div class="modal fade modal-vertical-middle" data-show="true"  data-backdrop="static" data-keyboard="false" id="product-tryon-modal" tabindex="-1">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<span>{{ text_3dtryon }}</span>
					<div class="cancel-tryon pull-right">{{ text_cancel_tryon }}</div>
				</div>
				<div class="modal-body">
					<div id="tryon_stage" class="tryon-stage"></div>
					<div class="tryon-control-bar">
						<div class="clear-all-glasses"></div>
						<div id="tryon-glass-swiper" class="swiper-container tryon-glasses-list">
							{#swiper的控制栏#}
							<div class="swiper-wrapper"></div>
							<div class="swiper-pager">
								<div class="swiper-button-prev tryon-glasses-prev"></div>
								<div class="swiper-button-next tryon-glasses-next"></div>
							</div>
						</div>
					</div>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal -->
	</div>

	<!-- 预览模态框（Modal） -->
	<div class="modal fade modal-vertical-middle" id="photo-modal" tabindex="1">
		<div class="modal-dialog">
		</div><!-- /.modal -->
	</div>

</div>

<script src="/catalog/view/javascript/jquery/swiper/js/swiper.min.js"></script>
<script src="https://tryon.xiaojingxiuxiu.com/lib/three.r90.min.js"></script>

{#<script src="/catalog/view/javascript/gl-tryon.min.js"></script>#}
<script src="https://tryon.xiaojingxiuxiu.com/lib/gl-tryon.min.js"></script>

<script type="text/javascript"><!--
    jQuery(document).ready(function($) {
        $('#review').load('index.php?route=product/product/review&product_id={{ product_id }}');

        $('.quantity-input-wrapper a').click(function(e) {
            e.preventDefault();
            if( $(this).hasClass('quantity-up')) {
                $('#input-quantity').val( parseInt($('#input-quantity').val()) + 1 );
            } else {
                if( parseInt($('#input-quantity').val())  > {{ minimum }} ) {
                    $('#input-quantity').val( parseInt($('#input-quantity').val()) - 1 );
                }
            }
        });

        $('#button-cart').productInfoToCart({
            data: [
                '#product input[type=\'text\']',
                '#product input[type=\'hidden\']',
                '#product input[type=\'radio\']:checked',
                '#product input[type=\'checkbox\']:checked',
                '#product select, #product textarea'
            ]
        });

        if ($(window).width() >= 768) {
            $('#elevate-zoom').elevateZoom({
                lensShape: 'basic',
                lensSize: 150,
                zoomWindowOffetx: 10,
                zoomWindowWidth: 450,
                zoomWindowHeight: 450,
                borderSize: 1,
                borderColour: '#eaeaea',
                gallery: 'product-thumbnail-gallery',
                galleryActiveClass: 'active',
                cursor:'pointer'
            });

            $('#elevate-zoom').bind('click', function(e) {
                var ez = $('#elevate-zoom').data('elevateZoom');
                $.fancybox(ez.getGalleryList());
                return false;
            });
        } else {
            $('.elevatezoom-gallery').fancybox({
                openEffect : 'none',
                helpers : {
                    title : null
                }
            });
            $('.elevate-zoom-preview a').bind('click', function(e) {
                $('.elevatezoom-gallery').eq(0).trigger('click');
                return false;
            });
        }
        // 此处存在问题，如果网速过慢，控制台会log一条来自jquery.elevateZoom.min.js的错误
        setTimeout(function(){
            $('.elevatezoom-gallery').eq(0).trigger('click');
        },1000);

        // 试戴弹框的处理逻辑
        (function tryOnHandle(){
            var $tryon_modal = $('#product-tryon-modal');
            var tryon_open_btn = $('.tryon-button');
            var tryon_close_btn = $('.cancel-tryon');

            // 是否提前关闭了试戴实例
			var is_early = false;

            // 缓存试戴模型
			var models = [];

            var NO_GLASS = -1;// 没有眼镜试戴时的常量

            // 试戴的状态变量
            var sdk_ready = false;
            var first_loaded = false;

            // 试戴的初始眼镜的index
            var current_index = 0;

            // 打开摄像头的视频流对象
            var video_stack;

            // 试戴实例
            var pkxTryOn;

            // swiper实例
            var tryon_glasses_swiper;

            var assets_api_url = '/index.php?route=product/tryon/glassJson&product_id={{ product_id }}';

            tryon_open_btn.click(function() {
                if( models.length === 0 )return fetchTryonAssets();

                initGlassList();
                initGlassTryon();
			});

            tryon_close_btn.click(function() {
                if( !pkxTryOn )return;
                $tryon_modal.modal('hide');
                if( !sdk_ready ){
                    is_early = true;
				}
                if(video_stack)video_stack.getTracks()[0].stop();
            });

            // 清除所有试戴的眼镜
            $('.clear-all-glasses').click(function() {
                if(!pkxTryOn)return;
                $('#tryon-glass-swiper .swiper-slide img.selected').removeClass('selected');
                current_index = NO_GLASS;
                pkxTryOn.hideGlass();
            });

            /**
             * 获取试戴素材
             * */
            function fetchTryonAssets() {
                $.ajax({
                    url: assets_api_url,
                    type: 'get',
                    dataType: 'json',
                    success: function(response) {
                        if( parseInt(response.code) === 0 ) {
                            models = response.models;
                            initGlassList();
                            initGlassTryon();
                            $tryon_modal.modal('show');
                        }
                    },
                    error: function (error) {
                        layer.open({
                            skin: 'layer-alert',
                            btnAlign: 'c',
                            title: ' ',
                            content: error.message
                        });
                    }
                });
            }

            /**
             * 初始化3d眼镜试戴
             * */
            function initGlassTryon() {

                var first_glass = models[0].name;

                if( !pkxTryOn ){
                    pkxTryOn = new GLTryOn({
                        stage: "#tryon_stage" ,
                        size: {
                            width: 940,
                            height: 540
                        },
                        glasses: models
                    });

                    block_section('#tryon_stage');

                    pkxTryOn
                        .on("ready", function (video) {
                            video_stack = video;
                            unblock_section('#tryon_stage');
                            console.info("gl tryon ready!");
                            sdk_ready = true;
                            console.log(is_early);
                            if( is_early ){
                                is_early = false;
                                video_stack.getTracks()[0].stop();
                                return;
                            }
                            $tryon_modal.modal('show');
                            onReady(models);
                        })
                        .on("error", function (error_type, error_msg) {
                            unblock_section('#tryon_stage');
                            console.info(error_type, error_msg);
                            // alert(error_type + ':' + error_msg);
                            var err_str;
                            if( error_type === 'CAMERA_ERROR' ) {
                                err_str = '<p style="margin-bottom: 0"><i style="color: #F06767;font-size: 16px;margin-right: 5px;" class="fa fa-info-circle"></i>{{ error_capture }}</p>';
                            }else {
                                err_str = '<p style="margin-bottom: 0"><i style="color: #F06767;font-size: 16px;margin-right: 5px;" class="fa fa-info-circle"></i>{{ error_msg }}</p>';
                            }

                            layer.open({
                                skin: 'layer-alert',
                                btnAlign: 'c',
                                title: ' ',
                                content: err_str
                            });

                            $tryon_modal.modal('hide');
                        })
                        .on("glass-loaded", function (glass) {
                            if (glass.name === first_glass) {
                                first_loaded = true;
                                onReady();
                            }
                            var loaded_glass = models.filter(function(model){
                                return model.name === glass.name;
							})[0];
                            loaded_glass.loaded = true;

                            if( models[current_index].name === glass.name && sdk_ready ){
                                unblock_section('#tryon_stage');
							}
                            console.info(glass.name + " loaded");
                        });
                }else {
                    pkxTryOn.startCamera();
                }
            }

            /**
             * 试戴实例对象初始化完成后触发的方法
             * */
            function onReady() {
                if (sdk_ready && first_loaded && models[current_index]) {
                    var first_glass = models[current_index].name;
                    pkxTryOn.changeGlass(first_glass);
                    selectSlide(current_index);
                }
            }

            /**
             * 初始化眼镜列表
             * @param array models 眼镜模型数组
             * */
            function initGlassList(){
                if(!models || models.length === 0)return;

                if(!tryon_glasses_swiper) {
                    var control_str = '';

                    models.forEach(function(model,index){
                        control_str += '<div class="swiper-slide swiper-no-swiping text-center"><a><img src="' + model.preview + '" ' +
                            'alt="' + model.name +'" class="glass-img" data-index="' + index + '">' + '</a><p>' + model.name +'</p></div>';
                    });

                    $('.swiper-wrapper').html(control_str);

                    addClickForSwiperSlide(models);

                    initSwiper();
                }else {
                    tryon_glasses_swiper.update(true);
                }
            }

            /**
             * 初始化swiper实例
             * */
            function initSwiper() {
                tryon_glasses_swiper = new Swiper('#tryon-glass-swiper', {
                    width: 817,
                    slidesPerView: 6,
                    roundLengths : true,
                    autoplay: false,
                    navigation: {
                        nextEl: '.tryon-glasses-next',
                        prevEl: '.tryon-glasses-prev'
                    },
                    spaceBetween: 8,
                    preventClicks: false
                });
            }

            /**
             * 给swiper的每个silde添加点击事件
             * */
            function addClickForSwiperSlide(models) {
                $('#tryon-glass-swiper .swiper-slide').click(function(e){
                    if( current_index === e.target.dataset.index )return;
                    current_index = e.target.dataset.index;

                    if( !models[current_index] )return;

                    var current_glass = models[current_index].name;

                    selectSlide(current_index);

                    if( !models[current_index].loaded || !sdk_ready ){
                        return block_section('#tryon_stage');
                    }else {
                        unblock_section('#tryon_stage');
					}

                    pkxTryOn.changeGlass(current_glass);
                })
            }

            /**
             * 选中silde执行的逻辑处理函数
             * */
            function selectSlide(index) {
                $('#tryon-glass-swiper .swiper-slide img.selected').removeClass('selected');
                $('#tryon-glass-swiper .swiper-slide img').eq(index).addClass('selected');
            }

        })();

        /**
         * 锁定区域，显示loading
         * @param string section_id 需要锁定的区域的选择器名称
         * */
        function block_section(section_id) {
            if (!$(section_id).children('.loading-mask').length) {
                $(section_id).append('<div class="loading-mask"><i class="fa fa-spinner fa-spin"></i></div>');
            }
            $('#button-submit').prop('disabled', true);
        }

        /**
         * 解锁区域，取消loading
         * @param string section_id 需要解锁的区域的选择器名称
         * */
        function unblock_section(section_id) {
            if( !$(section_id).children('.loading-mask') )return;
            $(section_id).children('.loading-mask').remove();
        }
    });
    //--></script>


{% if product_video_url %}
    {#@link https://github.com/MoePlayer/DPlayer#}
    <link rel="stylesheet" href="/catalog/view/javascript/libs/DPlayer/DPlayer.min.css">
    <script type="text/javascript" src="/catalog/view/javascript/libs/DPlayer/DPlayer.min.js"></script>
    <script type="text/javascript">
        // 播放器
        $(function () {
            var $elevateZoomPreview = $(".elevate-zoom-preview"); // 放大镜
            var $playerWrapper = $("#player-wrapper"); // 播放器盒子
            var $play = $("#player-play"); // 播放按钮
            var $close = $("#player-close"); // 关闭按钮
            /**
             *  初始化播放器
             */
            var dp = new DPlayer({
                container: document.getElementById("player-content"),
                video: {
                    url: '{{ product_video_url }}',
                },
                theme: '#222222',
                loop: false,
            });

            /**
             *  处理可以播放事件
             */
            dp.on('canplay', function () {
                $play.show();
                setPlayerSize();
            });

            /**
             * 隐藏播放器
             */
            $("#product-thumbnail-gallery").hover(hidePlayer);
            $close.click(hidePlayer);

            /**
             * 展示播放器
             */
            $("#player-play").click(showPlayer);

            /**
             *  展示播放器
             */
            function showPlayer() {
                dp.play();
                $elevateZoomPreview.hide();
                $playerWrapper.show();
                $play.hide();
                $close.show();
                $(".dplayer-setting").hide();
            }

            /**
             * 展示播放器
             */
            function hidePlayer(){
                dp.pause();
                $playerWrapper.hide();
                $elevateZoomPreview.show();
                $close.hide();
                $play.show();
            }

            /**
             *  设置播放器的尺寸
             */
            function setPlayerSize(){
                $playerWrapper.css({
                    width: $elevateZoomPreview.innerWidth(),
                    height: $elevateZoomPreview.innerWidth(),
                });
            }

            /**
             * 处理浏览器 resize 事件
             */
            $(window).resize(setPlayerSize);
        })
    </script>
{% endif %}

{% if reviews %}
    <script type="text/javascript">
        $(function(){
            /**
             *  监听已经被上传的图片的点击时事件
             */
            $('body').on('click', '.review-image .mask',  function (event) {
                var img = $(event.currentTarget).parents('.review-image').children('img');
                if (img.attr('src')){
                    previewImage(img.attr('src'));
                }
            });

            /**
             * 预览图片图片
             * @param src
             */
            function previewImage(src) {
                var $photoModal =  $("#photo-modal");
                $photoModal.find(".modal-dialog").html('');
                $photoModal.find('.modal-dialog').append("<img class='preview-image' src=\""+src+"\">");
                $photoModal.modal('show');
            }

            /**
             * 监听预览图片的模态框关闭的事件
             */
            $("#photo-modal").on('hide.bs.modal', function (event) {
                var $modal = $(event.currentTarget);
                $modal.find(".modal-dialog").html('');
            })
        })
    </script>
{% endif %}

{{ footer }}
